package drds.global_transaction.api.message_codec.request_and_response.register_manager;

import drds.global_transaction.api.message_codec.ResponseMessage;
import drds.global_transaction.api.message_codec.Version;
import io.netty.buffer.ByteBuf;
import lombok.Getter;
import lombok.Setter;

import java.nio.ByteBuffer;

public abstract class RegisterManagerResponseMessage extends ResponseMessage
{
	private static final long serialVersionUID = 1L;
	@Setter
	@Getter
	private String version = Version.current;;
	@Setter
	@Getter
	private String extraData;
	@Setter
	@Getter
	private boolean success;

	@Override
	public boolean decode(ByteBuf byteBuf)
	{
		int readableBytes = byteBuf.readableBytes();
		if (readableBytes < 3)
		{
			return false;
		}
		readableBytes -= 3;
		this.success = (byteBuf.readByte() == 1);

		short length = byteBuf.readShort();
		if (length > 0)
		{
			if (readableBytes < length)
			{
				return false;
			}

			byte[] bytes = new byte[length];
			byteBuf.readBytes(bytes);
			this.setVersion(new String(bytes, UTF8));
		}

		return true;
	}

	@Override
	public ByteBuffer putBytesToByteBuffer()
	{
		ByteBuffer byteBuffer = createByteBuffer();
		byteBuffer.put(this.success ? (byte) 1 : (byte) 0);
		if (this.version != null)
		{
			byte[] bytes = version.getBytes(UTF8);
			byteBuffer.putShort((short) bytes.length);
			if (bytes.length > 0)
			{
				byteBuffer.put(bytes);
			}
		} else
		{
			byteBuffer.putShort((short) 0);
		}
		//
		markAsEncode();
		return byteBuffer;

	}
}
